<template>
  <div class="box">
    <div>
      <!-- <div class="btnGroup">
        <div
          class="btn"
          :class="activeBtn == 1 ? 'active' : ''"
          @click="activeBtn = 1"
        >
          {{ $t("GameCurrency") }}
        </div>
        <div
          class="btn"
          :class="activeBtn == 2 ? 'active' : ''"
          @click="activeBtn = 2"
        >
          {{ $t("wallet") }}
        </div>
      </div> -->
      <div>
        <div class="recharge">
          <ul class="list-ul" v-if="list.length > 0">
            <li
              v-for="item of list"
              :key="item.id"
              @click="goPay(item)"
              :class="activeAmount == item.price ? 'active' : ''"
              :style="item.checked ? 'background: #aab6e8' : ''"
            >
              {{ item.price }} {{ item.currency }}
            </li>
          </ul>
          <p v-else class="noData">{{ $t("noData") }}</p>
          <div class="pay-way-box" v-if="payWayShow" v-loading="loading">
            <div
              :fullscreen="true"
              v-loading.lock="payLoading"
              class="loading-content"
              v-if="payLoading"
            ></div>
            <div class="title">{{ $t("paymentMethod") }}</div>
            <ul class="pay-way-list">
              <li
                class="pay-way"
                v-for="(item, index) in channel"
                :key="index"
                @click="goShop(item.pay_channel)"
              >
                <div>
                  {{ item.title }}
                </div>
              </li>
            </ul>
          </div>
        </div>
      </div>
      <!-- <div v-if="activeBtn == 2 && is_wallet == 1">
        <div class="rechargeInfo">
          <h4>{{ $t("walletBalance") }}：{{ available }} {{ coin_name }}</h4>
          <p>{{ $t("rate") }}：1 USDT = 1USD</p>
          <p>
            {{ $t("walletTips1") }}
          </p>
        </div>
        <div class="recharge">
          <ul class="list-ul" v-if="walletList.length > 0">
            <li
              v-for="item of walletList"
              :key="item.id"
              @click="goPay(item)"
              :class="activeAmount == item.price ? 'active' : ''"
              :style="item.checked ? 'background: #aab6e8' : ''"
            >
              {{ item.currency_symbol }} {{ item.price }}
            </li>
          </ul>
          <p v-else class="noData">{{ $t("noData") }}</p>
          <p
            v-if="activeAmount && activeBtn == 2 && is_wallet == 1"
            class="amountText"
          >
            {{ $t("haveAmount") }}: {{ activeAmount }} USD
          </p>
        </div>
        <div class="rechargeBtn" v-if="activeAmount">
          <div class="btn" @click="toRecharge" v-loading="btnLoading">
            {{ $t("toRecharge") }}
          </div>
        </div>
      </div>
      <div v-if="activeBtn == 2 && is_wallet == 0">
        <div class="noWallet">
          <h4 class="title">{{ $t("openWallet") }}</h4>
          <el-divider></el-divider>
          <div class="content">
            <el-form
              :model="form"
              label-position="top"
              :rules="rules"
              ref="ruleForm"
            >
              <el-form-item :label="$t('walletEmail')" prop="bind_email">
                <el-input
                  v-model="form.bind_email"
                  :placeholder="$t('walletEmailTip')"
                  style="width: 50%"
                ></el-input>
              </el-form-item>
              <el-form-item :label="$t('walletPsd')" prop="bind_password">
                <el-input
                  v-model="form.bind_password"
                  :placeholder="$t('walletPsdTip')"
                  style="width: 50%"
                ></el-input>
              </el-form-item>
            </el-form>
            <div class="openWalletBtn">
              <el-button
                type="primary"
                @click="openWallet('ruleForm')"
                class="openWallet"
                v-loading="btnLoading"
                >{{ $t("openWallet") }}</el-button
              >
            </div>
          </div>
        </div>
      </div> -->
    </div>
  </div>
</template>
<script>
import {
  httpGetChannel,
  httpInfo,
  httpGoodsList,
  httpPlaceOrder,
  httpWalletRecharge,
  httpWalletBalance,
} from "@/http/api";
import { formatMoney } from "@/utils/common";
export default {
  name: "recharge",
  props: {
    btnActive: {
      type: Number,
      default: 1,
    },
  },
  data() {
    return {
      value: 0,
      listLoading: false,
      ways2: [], // 默认支付方式
      selectItem: {}, // 选中的支付方式
      deleModal: false, // 删除弹窗是否展示
      paysAjax: false,
      assets_total: 0,
      disabled: true,
      list: [],
      walletList: [
        {
          id: 1,
          currency_symbol: "USDT",
          price: 10,
        },
        {
          id: 2,
          currency_symbol: "USDT",
          price: 20,
        },
        {
          id: 3,
          currency_symbol: "USDT",
          price: 40,
        },
        {
          id: 4,
          currency_symbol: "USDT",
          price: 70,
        },
        {
          id: 5,
          currency_symbol: "USDT",
          price: 100,
        },
        {
          id: 6,
          currency_symbol: "USDT",
          price: 200,
        },
        {
          id: 7,
          currency_symbol: "USDT",
          price: 400,
        },
        {
          id: 8,
          currency_symbol: "USDT",
          price: 600,
        },
        {
          id: 9,
          currency_symbol: "USDT",
          price: 1000,
        },
        {
          id: 10,
          currency_symbol: "USDT",
          price: 1800,
        },
        {
          id: 11,
          currency_symbol: "USDT",
          price: 3600,
        },
      ],
      goods_tip: "",
      pages: {
        // 分页信息
        page: 1,
        total: 0,
        nodata: false,
      },
      amount: null,
      channel: [],
      payWayShow: false,
      activeAmount: "",
      payAmount: null,
      payWay: "",
      loading: false,
      btnLoading: false,
      activeBtn: 1,
      is_wallet: 0,
      form: { bind_email: "", bind_password: "" },
      rules: {
        bind_email: [
          {
            required: true,
            message: this.$t("walletEmailTip"),
            trigger: "change",
          },
        ],
        bind_password: [
          { required: true, validator: this.checkPwd, trigger: "blur" },
        ],
      },
      available: 0,
      coin_name: "USDT",
    };
  },
  created() {
    this.loading = true;
    Promise.all([this.getHttpGoodsList(), this.getHttpInfo()])
      .then((res) => {
        console.log(res);
        this.loading = false;
      })
      .catch((err) => {
        console.log(err);
        this.loading = false;
      });
  },
  watch: {
    btnActive: {
      handler(val) {
        this.activeBtn = val;
      },
      immediate: true,
    },
  },
  methods: {
    getBalance() {
      httpWalletBalance().then((res) => {
        this.available = res.data.available || 0;
        this.coin_name = res.data.coin_name || "USDT";
      });
    },
    checkPwd(rule, value, callback) {
      if (!value) {
        callback(new Error(this.$t("walletPsdTip")));
      } else {
        const checkPwdFormat = new RegExp(/^[0-9a-zA-Z]{6,16}$/);
        if (!checkPwdFormat.test(value)) {
          callback(new Error(this.$t("walletPsdTip1")));
          return;
        }
        callback();
      }
    },
    formatMoney,
    handleInput(value) {
      // 如果输入值小于 10，则将其设为 10
      if (value < 10) {
        this.amount = 10;
      } else {
        this.amount = value;
      }
    },
    goPay(item) {
      if (this.activeBtn == 1) {
        this.payAmount = item;
        this.getHttpGetChannel();
        this.payWayShow = true;
        this.activeAmount = item.price;
      } else {
        this.activeAmount = item.price;
      }
    },
    async goShop(payWay) {
      this.payWay = payWay;
      const { goods_id } = this.payAmount;
      const res = await httpPlaceOrder({ goods_id, pay_channel: this.payWay });
      if (res.code === 0) {
        if (this.payWay.includes("USDT")) {
          this.$router.push({
            name: "payment",
            params: {
              item: JSON.stringify(res.data),
            },
          });
        } else {
          window.open(res.data.jump_url);
        }
      }
    },
    async getHttpInfo() {
      let res = await httpInfo();
      if (res.code == 0) {
        this.assets_total = res.data?.diamond || 0;
        this.is_wallet = res.data?.is_wallet || 0;
        this.form.bind_email = res.data?.account_name || "";
        if (this.is_wallet == 1) {
          this.getBalance();
        }
      }
    },
    async getHttpGoodsList() {
      let params = {
        page: this.pages.page,
      };
      const res = await httpGoodsList(params);
      if (res.code == 0) {
        this.list = [...this.list, ...(res.data.list || [])];
        this.goods_tip = res.data?.goods_tip.replace(/\n/g, "<br/>");
        this.pages.total = res.data.page.total_count;
        if (this.list.length < this.pages.total) this.pages.page++;
        if (!this.pages.total) this.pages.nodata = true;
      }
    },
    // 获取支付通道
    async getHttpGetChannel() {
      try {
        this.payLoading = true;
        let res = await httpGetChannel();
        if (res.code == 0) {
          this.channel = res.data || [];
          if (this.channel.length > 0) {
            this.payWay = this.channel[0].pay_channel;
          }
        }
        this.payLoading = false;
      } catch {
        this.payLoading = false;
      }
    },
    async toRecharge() {
      this.btnLoading = true;
      // 调接口  成功 messge提示，否则messagebox提示
      const res = await httpWalletRecharge({ amount: this.activeAmount });
      this.btnLoading = false;
      if (res.code == 0) {
        this.$message({
          type: "success",
          dangerouslyUseHTMLString: true,
          message: this.$t("rechargeSuccess", { amount: this.activeAmount }),
          center: true,
          showClose: true,
          iconClass: " ", // 这个会覆盖图标类名，为了实现去掉图标的操作
          customClass: "el-message--success", // 这个是由于上面设置了iconClass会覆盖掉type，所以需要再设置
        });
        this.getBalance();
        this.$emit("child-event");
      } else {
        if (res.code == 10293) {
          this.$confirm(this.$t("rechargeTip"), "", {
            dangerouslyUseHTMLString: true,
            confirmButtonText: "Ok",
            cancelButtonText: this.$t("cancel"),
            type: "warning",
            center: true,
            iconClass: " ", // 这个会覆盖图标类名，为了实现去掉图标的操作
            customClass: "el-message--warning", // 这个是由于上面设置了iconClass会覆盖掉type，所以需要再设置
          })
            .then(() => {
              this.$router.push("/walletRecharge");
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: this.$t("cancel"),
              });
            });
        } else {
          this.$message.error(res.message);
        }
      }
    },
    // openWallet(formName) {
    //   this.$refs[formName].validate((valid) => {
    //     if (valid) {
    //       const res = httpWalletBind(this.form);
    //       this.is_wallet = res.data?.is_wallet || 0;
    //       if (this.is_wallet == 1) {
    //         this.getBalance();
    //       }
    //     } else {
    //       console.log("error submit!!");
    //       return false;
    //     }
    //   });
    // },
  },
};
</script>
<style lang="less" scoped>
.box {
  position: relative;
  width: 100%;
  min-height: 400px;
}
.loading-content {
  display: flex;
  justify-content: center;
  align-items: center;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
.btnGroup {
  padding: 10px 0 20px;
  display: flex;
  justify-content: start;
  align-items: center;
  .btn {
    width: 180px;
    height: 40px;
    background-color: #e6e6e6;
    text-align: center;
    line-height: 40px;
    border-radius: 5px;
    margin-right: 10px;
    cursor: pointer;
  }
  .active {
    background-color: #513316;
    color: #fff;
  }
}
.recharge {
  padding: 20px;
  background: #fff;
  border-radius: 10px;
}
.rechargeInfo {
  padding: 20px;
  background: #fff;
  border-radius: 10px;
  margin-bottom: 10px;
  h4 {
    margin-bottom: 10px;
    font-size: 20px;
  }
  p,
  span {
    margin-bottom: 10px;
    color: rgb(127, 127, 127);
  }
}
.rechargeBtn {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
  .btn {
    width: 180px;
    height: 50px;
    background-color: #513316;
    color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 5px;
    cursor: pointer;
  }
}
.list-ul {
  display: grid;
  grid-template-columns: repeat(auto-fill, 20%);
  justify-content: space-between;
  gap: 10px;
  li {
    width: 100%;
    background: #e6e6e6;
    border-radius: 10px;
    padding: 15px;
    text-align: center;
    box-sizing: border-box;
    cursor: pointer;
  }
  .active {
    background: #efcd2e;
    color: #fff;
  }
}
.amountText {
  margin-top: 35px;
  margin-bottom: 10px;
  font-size: 20px;
}
.noData {
  text-align: center;
  font-size: 20px;
  color: #777;
}
.rechargeSearch {
  margin-top: 15px;
}

.pay-way-box {
  margin-top: 30px;
  position: relative;
  .loading-content {
    display: flex;
    justify-content: center;
    align-items: center;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
  .title {
    display: inline-block;
    font-size: 16px;
    height: 60px;
    flex-shrink: 0;
    font-weight: 500;
  }
  .pay-way-list {
    display: grid;
    grid-template-columns: repeat(auto-fill, 30%);
    justify-content: space-between;
    gap: 10px;
    .pay-way {
      width: 100%;
      height: 100%;
      background: #ced4f8;
      border-radius: 10px;
      padding: 10px;
      text-align: center;
      box-sizing: border-box;
      display: flex;
      justify-content: center;
      align-items: center;
      border-radius: 15px;
      margin-bottom: 20px;
      cursor: pointer;
    }
  }
}
.noWallet {
  background-color: #fff;
  height: 100%;
  width: 100%;
  .title {
    padding: 20px 20px 0;
  }
  .content {
    padding: 0 20px 20px;
    background-color: #fff;
  }
  .openWalletBtn {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    margin-top: 40px;
    .openWallet {
      width: 120px;
      display: flex;
      justify-content: center;
      align-items: center;
      background-color: #513216;
      border-radius: 5px;
      font-size: 12px;
      color: #fff;
      cursor: pointer;
    }
  }
}
</style>
